<?php
namespace app\api\controller\admin;

use app\admin\model\Admin;
use app\admin\model\dts\fault\Repair as FaultRepair;
use app\common\controller\TApi;
use Exception;
use think\Db;
use think\Log;

class Repair extends TApi {

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    //查询是维修的人员
    public function repairPersonnel() {
    
        $apiService = new \app\api\controller\Service;
        $list = $apiService->specialList(629);
        
        $this->success('success', $list);
    }

    //---------------------------------------------------------------------------------------------------------------------------------------------------------
    
    //维修记录
    public function repairLog() {
        
        $status = $this->request->get('status'); //0=待分配 1=待维修 2=已维修 3=已撤回
        $query1 = $status >= 0 ? ['log.status' => $status] : [];
        $category = $this->request->get('category');
        $query2 = $category ? ['log.category' => $category] : [];
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $query3 = [];
        if(!$this->auth->isAdmin()) {
            $admin = $this->auth->getAdmininfo();
            $apiService = new \app\api\controller\Service;
            $temp = $apiService->specialList(628, $admin['id']);
            if(!$temp) {
                $query3 = ['log.repair_id' => $admin['id']];
            }
        }

        $list = Db::name('dts_fault_repair')->alias('log')
        ->field('log.*,FROM_UNIXTIME(log.createtime,"%Y-%m-%d %H:%i") as createtime,admin.nickname as adminfame,repair.nickname as repairfame')
        ->join([
            ['admin admin', 'admin.id = log.admin_id', 'left'],
            ['admin repair', 'repair.id = log.repair_id', 'left']
        ])
        ->where(array_merge($query1, $query2, $query3))
        ->order('log.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //维修详情
    public function repairInfo() {
        
        $admin = $this->auth->getAdmininfo();
        $logId = $this->request->get('logId', 0);
        
        $info = Db::name('dts_fault_repair')->alias('log')
        ->field('log.*,FROM_UNIXTIME(log.createtime,"%Y-%m-%d %H:%i") as createtime,admin.nickname as adminfame,repair.nickname as repairfame')
        ->join([
            ['admin admin', 'admin.id = log.admin_id', 'left'],
            ['admin repair', 'repair.id = log.repair_id', 'left']
        ])
        ->where('log.id', $logId)
        ->find();

        if($info) {
            \app\admin\model\dts\todo\Items::where(['approve_id' => $logId, 'admin_id' => $admin['id'], 'category' => 'repair'])->update(['status' => 1]);
        }

        $this->success('success', $info);
    }

    //维修分配
    public function repairAllocation() {

        $logId = $this->request->post('logId', 0);
        $repairId = $this->request->post('repairId');
        $num = Db::name('admin')->where('id', $repairId)->count(1);
        if(!$num) {
            $this->error('未找到维修人员');
        }
        $repair = Db::name('dts_fault_repair')->where('id', $logId)->find();
        if(!$repair) {
            $this->error('未找到维修信息');
        }
        
        $apiService = new \app\api\controller\Service;

        __db(function() use($apiService, $repair, $repairId) {
           //处理待办事项
            if($repair['todo_ids']) {
                $apiService->handletodoitem(explode(',', $repair['todo_ids']));
            }
            $todo = $apiService->savetodoitem($repair['name'] ? $repair['name'] : $repair['location'], 'repair', $repairId);
            Db::name('dts_fault_repair')->where('id', $repair['id'])->update(['todo_ids' => $todo['id'], 'status' => FaultRepair::STATUS_1, 'repair_id' => $repairId]);
        });
        
        try {
            $apply = \app\admin\model\Admin::where('id', $repair['admin_id'])->find();

            $weChatData = ['time3' => date("Y-m-d H:i:s", time()), 'thing5' => $apply['nickname'], 'thing6' => mb_substr($repair['describes'], 0, 20, 'utf-8'), 'thing9' => mb_substr($repair['location'], 0, 20, 'utf-8')];
            //推送公众号
            $apiService = new \app\api\controller\Service;
            $apiService->wechatmessage($repairId, $apiService->template3, $apiService->jumpUrl('repair').'?type=detail&id='.$repair['id'], $weChatData);
        }catch(Exception $e) {
            Log::write($e->getMessage());
        }

        $this->success('success');
    }

    //维修确认
    public function repairVerify() {

        $logId = $this->request->post('logId', 0);
        $repair_msg = $this->request->post('repair_msg');//处置结果
        $repair_files = $this->request->post('repair_files');//处置结果图片
        
        $repair = Db::name('dts_fault_repair')->where('id', $logId)->find();
        if(!$repair) {
            $this->error('未找到维修信息');
        }
        if($repair['status'] != 1) {
            $this->error('当前状态不能确认维修');
        }
        __db(function() use($repair, $repair_msg, $repair_files) {
            $apiService = new \app\api\controller\Service;
            if($repair['todo_ids']) {
                $apiService->handletodoitem(explode(',', $repair['todo_ids']));
            }
            Db::name('dts_fault_repair')->where('id', $repair['id'])->update(['status' => FaultRepair::STATUS_2, 'repair_time' => date("Y-m-d H:i:s", time()), 'repair_msg' => $repair_msg, 'repair_files' => $repair_files]);
        });
        
        $admin = $this->auth->getAdmininfo();

        //公众号消息
        $apiService = new \app\api\controller\Service;
        $weChatData = ['thing4' => mb_substr($repair['describes'], 0, 20, 'utf-8'), 'thing9' => mb_substr($repair['location'], 0, 20, 'utf-8'), 'thing8' => $admin['nickname'], 'const18' => '维修完成', 'time11' => date("Y-m-d H:i:s", time())];
        $apiService->wechatmessage($repair['admin_id'], $apiService->template4, $apiService->jumpUrl('repair').'?type=detail&id='.$repair['id'], $weChatData);
        
        $this->success('success');
    }
}